import datetime
import sys
from optparse import make_option

from product.models import Product, Price

from satchmo_tuning.models import CategoryTuning
from satchmo_tuning.management.commands import UploadCommand

class Command(UploadCommand):
    option_list = UploadCommand.option_list + (
        make_option('--shortly', action='store_true', dest='shortly',
            help='Set out of stock products as inactive'),
    )
    help = 'Update products data from specified CSV file.'

    def handle_reader(self, reader, site, encoding):

        shortly = self.options.get('shortly')

        row_count = 0
        for row in reader:
            row_count += 1
            if len(row) != 5:
                sys.stderr.write(self.style.ERROR("Wrong columns count for row %s %s\n" % (row_count, row)))
            category_code, code, name, items_in_stock, price = [unicode(c, encoding).strip() for c in row]

            category = self.get_category(category_code)
            if not category:
                sys.stderr.write(self.style.ERROR("Unknown category code [%s] at row %s\n" % (category_code, row_count)))
            else:
                try:
                    product = Product.objects.get(site=site, slug=code)
                    new_product = False
                except Product.DoesNotExist:
                    product = Product(site=site, slug=code)
                    new_product = True
                product.name = name
                product.items_in_stock = items_in_stock
                if shortly:
                    product.active = (items_in_stock > 0)
                product.save()

                if new_product or list(product.category.all().values_list('id', flat=True)) != [category.id]:
                    product.category = [category]
           
                prices = product.price_set.exclude(
                    expires__isnull=False,
                    expires__lt=datetime.date.today()).filter(quantity__lte=1)

                if new_product:
                    Price.objects.create(product=product, price=price)
                else:
                    price_list = list(prices)
                    if price_list:
                        price_list[0].price = price
                        price_list[0].save()
                    else:
                        Price.objects.create(product=product, price=price) 

        if shortly:
            for category in CategoryTuning.objects.filter(site=site):
                category.active = bool(category.child.all() or category.active_products())
                category.save()
